package com.yzh.wanandroid.repository.datasource

import android.util.Log
import androidx.paging.PagingSource
import com.yzh.wanandroid.network.retrofit.RetrofitFactory
import com.yzh.wanandroid.network.retrofit.api.DataServer
import com.yzh.wanandroid.network.retrofit.responsebean.BaseData
import com.yzh.wanandroid.network.retrofit.responsebean.BasePageData
import com.yzh.wanandroid.network.retrofit.responsebean.ListData
import com.yzh.wanandroid.utils.PAGER_HOME
import com.yzh.wanandroid.utils.PAGER_PROJECT
import com.yzh.wanandroid.utils.PAGER_PUBLIC
import com.yzh.wanandroid.utils.PAGER_SQUARE

class ListRepository(var type: Int) : PagingSource<Int, ListData>() {

    private val TAG = "ListRepository"

    private var mId: Int = 0

    constructor(type: Int, id: Int) : this(type) {
        this.mId = id
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ListData> {
        return try {
            var currentPage = params.key ?: 0
            Log.d(TAG, "当前为第${currentPage}页")
            var listData: BaseData<BasePageData<ListData>> = when (type) {
                PAGER_HOME -> {
                    RetrofitFactory.createApi(DataServer::class.java).getArticleList(currentPage)
                }
                PAGER_SQUARE -> {
                    RetrofitFactory.createApi(DataServer::class.java).getSquareList(currentPage)
                }
                PAGER_PUBLIC -> {
                    RetrofitFactory.createApi(DataServer::class.java)
                        .getPublicData(mId, currentPage)
                }
                PAGER_PROJECT -> {
                    RetrofitFactory.createApi(DataServer::class.java)
                        .getProjectItemList(currentPage, mId)
                }
                else -> {
                    RetrofitFactory.createApi(DataServer::class.java).getArticleList(currentPage)
                }
            }
            var nextPage = if (currentPage < listData.data.pageCount) {
                currentPage + 1
            } else {
                null
            }
            LoadResult.Page(
                data = listData.data.datas,
                prevKey = null,
                nextKey = nextPage
            )
        } catch (e: Exception) {
            Log.i(TAG, "Exception e = $e")
            LoadResult.Error(throwable = e)
        }
    }
}